package com.security.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.security.entity.Role;
import com.security.entity.User;
import com.security.mapper.UserMapper;
import com.security.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhuchao
 * @since 2021-03-27
 */
@Component
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService  {

	@Autowired
	private UserMapper userMapper;

	@Override
	public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

		if (s == null || "".equals(s))
		{
			throw new RuntimeException("用户不能为空");
		}
		// 调用方法查询用户
		User user = userMapper.findUserByUsername(s);
		if (user == null)
		{
			throw new RuntimeException("用户不存在");
		}
		List<SimpleGrantedAuthority> authorities = new ArrayList<>();
		for (Role role:userMapper.findRoleByUsername(s)){
			authorities.add(new SimpleGrantedAuthority("ROLE_"+role.getName()));
		}
		return new org.springframework.security.core.userdetails.User(user.getUsername(),"{noop}"+user.getPassword(),authorities);
	}
}
